package mypack.openworld;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.MyLocationOverlay;
import org.osmdroid.views.overlay.OverlayItem;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import overlay.ZoomedItemizedIconOverlay;


public class Map extends ActionBarActivity {

    private Location location = null;
    private LocationManager locationManager = null;
    private MyLocationOverlay myLocationOverlay = null;
    private LocationListener locationListener = null;
    static final int TAKE_PHOTO = 12345;
    Uri uriImage;

    public void onClickSightDetails (View view) {
        Intent intent = new Intent(this, Sight.class);
        startActivity(intent);
    }

    public void onClickTakePhoto (View view) {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File file = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
        uriImage = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uriImage);
        startActivityForResult(intent, TAKE_PHOTO);
    }

    @Override
    public void onActivityResult (int codeRequest, int codeResult, Intent intent) {
        super.onActivityResult(codeRequest, codeResult, intent);
        switch (codeRequest) {
            case TAKE_PHOTO:
                if (codeResult == Activity.RESULT_OK) {
                    Toast.makeText(this, "Photo has been made", Toast.LENGTH_LONG);
                    getContentResolver().notifyChange(uriImage, null);
                }
                else Toast.makeText(this, "Error", Toast.LENGTH_LONG);
                break;
        }
    }

    public void updateLocation (Location location) {
        this.location = location;
       // ((TextView) findViewById(R.id.tex)).setText("Долгота = " + location.getLongitude() + "; широта = " + location.getLatitude());
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("longitude", String.valueOf(location.getLongitude()));
        hashMap.put("latitude", String.valueOf(location.getLatitude()));
        String data = new Gson().toJson(hashMap);
        new ServerInteraction(new ServerResponseProcessor() {
            @Override
            public void process(String string) {
                ((TextView) findViewById(R.id.tex)).setText(string);
            }
        }).execute("/location.php", data);
    }

    public void onPause () {
        super.onPause();
        locationManager.removeUpdates(locationListener);
        if (myLocationOverlay != null) {
            myLocationOverlay.disableCompass();
            myLocationOverlay.disableFollowLocation();
            myLocationOverlay.disableMyLocation();
        }
    }

    public void onResume () {
        super.onResume();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
        initMap();
    }

    public void initMap () {
        MapView mapView = (MapView) findViewById(R.id.map);
        mapView.setBuiltInZoomControls(true);
        mapView.setMultiTouchControls(true);
        mapView.setTileSource(TileSourceFactory.MAPQUESTOSM);
        if (location == null) {
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location == null) {
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }
            updateLocation(location);
        }
        MapController mapController = mapView.getController();
        mapController.setZoom(18);
        mapController.animateTo(location.getLatitude(), location.getLongitude());
        if (myLocationOverlay == null) {
            myLocationOverlay = new MyLocationOverlay(this, mapView);
            mapView.getOverlays().add(myLocationOverlay);
        }
        myLocationOverlay.enableMyLocation();
        myLocationOverlay.enableFollowLocation();
        myLocationOverlay.enableCompass();
        myLocationOverlay.setDrawAccuracyEnabled(true);

        SightBoundaryPolygon myHome = new SightBoundaryPolygon(this, Color.GREEN);
        myHome.addPoint(new GeoPoint(59.729465, 30.413112));
        myHome.addPoint(new GeoPoint(59.729565, 30.413112));
        myHome.addPoint(new GeoPoint(59.729565, 30.413012));
        myHome.addPoint(new GeoPoint(59.729465, 30.413112));

        mapView.getOverlays().add(myHome.getOverlay());

        SightBoundaryCircle myHome2 = new SightBoundaryCircle(this, new GeoPoint(59.729465, 30.413112), 200, Color.BLUE, 70, Paint.Style.FILL_AND_STROKE);
        mapView.getOverlays().add(myHome2.getOverlay());

        ResourceProxy resourceProxy = new DefaultResourceProxyImpl(this);
        OverlayItem overlayItem = new OverlayItem("My home", ":)", new GeoPoint(59.729465, 30.413112));
        overlayItem.setMarker(this.getResources().getDrawable(R.drawable.home));
        ArrayList<OverlayItem> homes = new ArrayList<OverlayItem>();
        homes.add(overlayItem);
        ZoomedItemizedIconOverlay itemizedIconOverlay = new ZoomedItemizedIconOverlay<OverlayItem>(homes, new ItemizedIconOverlay.OnItemGestureListener<OverlayItem> () {
            @Override
            public boolean onItemSingleTapUp(int i, OverlayItem overlayItem) {
                return false;
            }

            @Override
            public boolean onItemLongPress(int i, OverlayItem overlayItem) {
                return false;
            }
        }, resourceProxy);
        mapView.getOverlays().add(itemizedIconOverlay);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                updateLocation(location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {}

            @Override
            public void onProviderEnabled(String provider) {}

            @Override
            public void onProviderDisabled(String provider) {}
        };
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.map, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}